import { BaseReactElementState, BaseReactElement, reactControl, BaseReactElementControl } from "pao-aop-client";
import React from "react";
import { addon } from "pao-aop";
import { WingBlank, WhiteSpace, Card, Button, Toast, Steps, Result, Icon } from "antd-mobile";
import { Row } from "antd";
import { AppServiceUtility } from "src/projects/app/appService";
import { ROUTE_PATH, PAGE_TYPE, encodeUrlParam } from "src/projects/app/util-tool";
import { request, getUuid } from "src/business/util_tool";
const Step = Steps.Step;
const myImg = (src: any) => <img src={src} className="spe am-icon am-icon-md" alt="" />;
/**
 * 组件：冠名基金详情状态
 */
export interface CharitableTitleFundInfoViewState extends BaseReactElementState {
    // 基金详情
    fund_info: any;
    // 募捐步骤
    apply_step: any;
    // 当前步骤
    step_no?: number;
    // 当前状态
    status?: string;
    // 重新获取的开关，只让拿一次
    reGet: boolean;
}

/**
 * 组件：冠名基金详情
 * 基金详情
 */
export class CharitableTitleFundInfoView extends BaseReactElement<CharitableTitleFundInfoViewControl, CharitableTitleFundInfoViewState> {
    constructor(props: any) {
        super(props);
        this.state = {
            fund_info: [],
            apply_step: [],
            step_no: -2,
            status: '未知',
            reGet: true,
        };
    }
    componentDidMount() {
        Toast.loading('Loading...', 1);
        this.reloadFunc();

        // 获取募捐步骤
        request(this, AppServiceUtility.charitable_service.get_recipient_step!({ 'step_type': '基金' }, 1, 1))
            .then((data: any) => {
                if (data) {
                    this.setState({
                        apply_step: data,
                    });
                } else {
                    Toast.fail(`错误信息：${data}`);
                }
            })
            .catch(error => {
                Toast.fail(error.message);
            });
    }
    backList = () => {
        this.props.history!.push(ROUTE_PATH.charitableTitleFundRecord);
    }
    goPay() {
        let fund_info = this.state.fund_info;
        if (fund_info['out_trade_no']) {
            // 已有第三方订单号
            this.payProccess(fund_info['out_trade_no']);
        } else {
            const out_trade_no: string = getUuid();
            // 更新第三方订单号
            request(this, AppServiceUtility.charitable_service.update_charitable_title_fund!({ 'out_trade_no': out_trade_no, id: this.props.match!.params.key }))
                .then((data: any) => {
                    if (data === 'Success') {
                        this.payProccess(out_trade_no);
                    } else {
                        Toast.fail(`错误信息：${data}`);
                    }
                })
                .catch(error => {
                    Toast.fail(error.message);
                });
        }
    }
    payProccess(out_trade_no: string) {
        // 前往支付流程
        let buy_param = JSON.stringify({
            page_type: PAGE_TYPE.DONATION,
            page_info: Number(this.state.fund_info.donate_money),
            abstract: '捐款',
            remarks: "冠名基金",
            out_trade_no: out_trade_no,
            product_desc: "冠名基金",
            // 附加信息（可选），微信异步通知会原样返回
            attach: "titlefund"
        });
        this.props.history!.push(ROUTE_PATH.payment + '/' + encodeUrlParam(buy_param));
    }
    reloadFunc = () => {
        request(this, AppServiceUtility.charitable_service.get_charitable_title_fund_list!({ all: true, id: this.props.match!.params.key }, 1, 1))
            .then((datas: any) => {
                Toast.hide();
                let step_no = (datas.result && datas.result[0] && datas.result[0]['new_field'] && datas.result[0]['new_field'][0] && datas.result[0]['new_field'][0]['step_no']) ? datas.result[0]['new_field'][0]['step_no'] : ((datas.result && datas.result[0] && datas.result[0]['step_no']) ? datas.result[0]['step_no'] : -1);
                let status = (datas.result && datas.result[0] && datas.result[0]['new_field'] && datas.result[0]['new_field'][0] && datas.result[0]['new_field'][0]['status']) ? datas.result[0]['new_field'][0]['status'] : ((datas.result && datas.result[0] && datas.result[0]['status']) ? datas.result[0]['status'] : '未知');
                let fund_info = (datas.result && datas.result[0]) || [];
                this.setState({
                    fund_info,
                    step_no,
                    status,
                });
                if (this.state.reGet === true && fund_info['out_trade_no'] && (fund_info['pay_status'] !== '已付款' || fund_info['status'] !== '通过')) {
                    this.checkPayStatus(fund_info['out_trade_no']);
                }
            }).catch((error: Error) => {
                Toast.fail(error.message);
            });
    }

    checkPayStatus(out_trade_no: string) {
        request(this, AppServiceUtility.charitable_service.checkPayStatus!({ out_trade_no: out_trade_no, checkType: 'titlefund' }))
            .then((datas: any) => {
                // 已付款重新获取数据
                if (datas === '已付款') {
                    this.setState(
                        {
                            reGet: false,
                        },
                        () => {
                            this.reloadFunc();
                        }
                    );
                }
            }).catch((error: Error) => {
                Toast.fail(error.message);
            });
    }
    notDo() {
        console.log('没事做');
    }
    render() {
        let { fund_info, status, apply_step, step_no } = this.state;
        step_no = step_no === -1 ? apply_step.length - 1 : step_no;
        let errStatus = status === '不通过' ? { status: "error" } : {};
        return (
            <Card>
                <WingBlank size="sm">
                    <WhiteSpace size="md" />
                    <Row type='flex' justify='center'>
                        <strong style={{ fontSize: '18px' }}>募捐流程</strong>
                    </Row>
                    {(() => {
                        if (status === '通过') {
                            return (
                                <Result
                                    img={<Icon type="check-circle" className="spe" style={{ fill: '#52C41A' }} />}
                                    title="通过"
                                />
                            );
                        } else if (status === '不通过') {
                            return (
                                <Result
                                    img={<Icon type="cross-circle-o" className="spe" style={{ fill: '#F13642' }} />}
                                    title="不通过"
                                    message={`原因：${fund_info.sp_msg}`}
                                />
                            );
                        } else {
                            return (
                                <Result
                                    img={myImg('https://gw.alipayobjects.com/zos/rmsportal/HWuSTipkjJRfTWekgTUG.svg')}
                                    title="待审批"
                                />
                            );
                        }
                    })()}
                    <div style={{ fontSize: '30px', paddingTop: '10px' }}>
                        {fund_info.apply_type === '个人'}
                        <Steps size="lg" {...errStatus} current={step_no} >
                            {apply_step.map((item: any, index: number) => {
                                return (
                                    <Step key={index} title={item.step_name} />
                                );
                            })}
                        </Steps>
                    </div>
                    <WhiteSpace size="md" />
                    <Row type='flex' justify='center'>
                        <strong style={{ fontSize: '18px' }}>基金信息</strong>
                    </Row>
                    <WhiteSpace size="xl" />
                    <Row type='flex' justify='start'>
                        <strong>基金名字</strong>
                    </Row>
                    <WhiteSpace size="xs" />
                    <Row>
                        {fund_info.donate_name || '无'}
                    </Row>
                    {/* <WhiteSpace size="xl" />
                        <Row type='flex' justify='start'>
                            <strong>捐款项目</strong>
                        </Row>
                        <WhiteSpace size="xs" />
                        <Row>
                            {fund_info.donate_project_name || '无'}
                        </Row> */}
                    <WhiteSpace size="xl" />
                    <Row type='flex' justify='start'>
                        <strong>基金金额</strong>
                    </Row>
                    <WhiteSpace size="xs" />
                    <Row>
                        {fund_info.donate_money || 0}
                    </Row>
                    <WhiteSpace size="xl" />
                    <Row type='flex' justify='start'>
                        <strong>已用金额</strong>
                    </Row>
                    <WhiteSpace size="xs" />
                    <Row>
                        {fund_info.payed_money || 0}
                    </Row>
                    {fund_info['status'] === '通过' ? <Row>
                        <WhiteSpace size="xl" />
                        <Row type='flex' justify='start'>
                            <strong>冻结金额</strong>
                        </Row>
                        <WhiteSpace size="xs" />
                        <Row>
                            {fund_info.freeze_money || 0}
                        </Row>
                        <WhiteSpace size="xl" />
                        <Row type='flex' justify='start'>
                            <strong>剩余金额</strong>
                        </Row>
                        <WhiteSpace size="xs" />
                        <Row>
                            {fund_info.surplus_money || 0}
                        </Row>
                    </Row> : null}
                    <WhiteSpace size="xl" />
                    <Row type='flex' justify='start'>
                        <strong>基金意向</strong>
                    </Row>
                    <WhiteSpace size="xs" />
                    <Row>
                        {fund_info.donate_intention || '无'}
                    </Row>
                    <WhiteSpace size="xl" />
                    <Row type='flex' justify='start'>
                        <strong>救助对象</strong>
                    </Row>
                    <WhiteSpace size="xs" />
                    <Row>
                        {fund_info.donate_object || '无'}
                    </Row>
                    <WhiteSpace size="xl" />
                    <Row type='flex' justify='start'>
                        <strong>联系方式</strong>
                    </Row>
                    <WhiteSpace size="xs" />
                    <Row>
                        {fund_info.contacts || '无'}
                    </Row>
                    <WhiteSpace size="xl" />
                    <Row type='flex' justify='start'>
                        <strong>支付状态</strong>
                    </Row>
                    <WhiteSpace size="xs" />
                    <Row>
                        {fund_info.pay_status || '无'}
                    </Row>
                    <WhiteSpace size="xl" />
                    <Row type='flex' justify='start'>
                        <strong>基金描述</strong>
                    </Row>
                    <WhiteSpace size="xs" />
                    <Row>
                        {fund_info.remark || '无'}
                    </Row>
                    <WhiteSpace size='xl' />
                    <Row type='flex' justify='start'>
                        <strong>开始时间</strong>
                    </Row>
                    <WhiteSpace size="xs" />
                    <Row>
                        {fund_info.begin_date || '无'}
                    </Row>
                    <WhiteSpace size='xl' />
                    <Row type='flex' justify='start'>
                        <strong>结束时间</strong>
                    </Row>
                    <WhiteSpace size="xs" />
                    <Row>
                        {fund_info.end_date || '无'}
                    </Row>
                    <WhiteSpace size='xl' />
                    <Row type='flex' justify='start'>
                        <strong>申请时间</strong>
                    </Row>
                    <WhiteSpace size="xs" />
                    <Row>
                        {fund_info.create_date || '无'}
                    </Row>
                    <WhiteSpace size="lg" />
                    {fund_info['status'] === '待审批' && fund_info['step_no'] === 2 ? <Row>
                        <WhiteSpace size="lg" />
                        <Button type="primary" onClick={() => this.goPay()}>支付</Button>
                    </Row> : null}
                    {fund_info['status'] === '通过' && fund_info['pay_status'] === '已付款' && fund_info['recipient_info'] ?
                        <Card>
                            <Card.Header
                                title="款项去向"
                            />
                            {fund_info['recipient_info'].length > 0 ? fund_info['recipient_info'].map((item: any, index: number) => {
                                return (
                                    <WingBlank key={index} size="lg">
                                        <WhiteSpace size="lg" />
                                        <Card.Body>
                                            <Row type='flex' justify='start'>
                                                <strong>募捐者</strong>
                                            </Row>
                                            <WhiteSpace size="xs" />
                                            <Row>
                                                {item.apply_name || '无'}
                                            </Row>
                                            <WhiteSpace size="xl" />
                                            <Row type='flex' justify='start'>
                                                <strong>使用金额</strong>
                                            </Row>
                                            <WhiteSpace size="xs" />
                                            <Row>
                                                {item.give_money || 0}
                                            </Row>
                                            <WhiteSpace size="xl" />
                                            <Row type='flex' justify='start'>
                                                <strong>募捐反馈</strong>
                                            </Row>
                                            <WhiteSpace size="xs" />
                                            <Row>
                                                {item.feedback || '暂无'}
                                            </Row>
                                            <WhiteSpace size='md' />
                                        </Card.Body>
                                    </WingBlank>
                                );
                            }) : <Row type="flex" justify="center">暂无使用记录</Row>}
                        </Card> : null
                    }
                    <WhiteSpace size="lg" />
                    <Button onClick={this.backList}>返回</Button>
                    <WhiteSpace size="lg" />
                    <WhiteSpace size="lg" />
                </WingBlank>
            </Card>
        );
    }
}

/**
 * 控件：冠名基金详情控制器
 * 基金详情
 */
@addon('CharitableTitleFundInfoView', '冠名基金详情', '基金详情')
@reactControl(CharitableTitleFundInfoView, true)
export class CharitableTitleFundInfoViewControl extends BaseReactElementControl {

}